import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
// 修改导入路径和函数名
import { renderAndSendMsgAuto } from '../resources/xr/xr.js';
import { handleTimeConfig } from '../modules/timeHandler.js';
import { addTaskToGroup, loadTimeConfig } from '../modules/timeconfig.js';
import { createLogger } from '../modules/Logger.js';
import ServerStatus from '../modules/mcapi.js';

// 获取当前文件路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 数据存储路径
const DATA_DIR = path.resolve(__dirname, '../data/mc');
const SUBSCRIPTIONS_FILE = path.join(DATA_DIR, 'mctj.json');
const BG_IMAGES_DIR = path.resolve(__dirname, '../data/背景图');
const BG_IMAGES_FILE = path.join(BG_IMAGES_DIR, 'square_images.json');

// 初始化数据存储目录和文件
if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR);
if (!fs.existsSync(SUBSCRIPTIONS_FILE)) fs.writeFileSync(SUBSCRIPTIONS_FILE, JSON.stringify({}));
if (!fs.existsSync(BG_IMAGES_DIR)) fs.mkdirSync(BG_IMAGES_DIR);
if (!fs.existsSync(BG_IMAGES_FILE)) fs.writeFileSync(BG_IMAGES_FILE, JSON.stringify([]));

// 获取当前本地日期（YYYY-MM-DD 格式）
function getLocalDate() {
    const now = new Date();
    return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`;
}

class ServerStatusPlugin extends plugin {
    constructor() {
        super({
            name: 'server_status',
            dsc: '服务器状态订阅与查询插件',
            event: 'message',
            priority: 500,
            rule: [
                { reg: "^m订阅 (.+)$", fnc: 'subscribeServer', permission: 'all' },
                { reg: "^m状态$", fnc: 'checkServerStatus', permission: 'all' },
                { reg: "^m取消订阅$", fnc: 'unsubscribeServer', permission: 'all' }
            ],
        });
        // 创建日志实例
        this.logger = createLogger(this.name);

        this.intervalConfig = loadTimeConfig().ServerStatusPlugin;
        this.autoStartTask();
    }

    // 订阅服务器（仅限群聊）
    subscribeServer(e) {
        // 限制指令只能在群聊中使用
        if (!e.isGroup) {
            return e.reply('此功能仅限群聊使用，请在群聊中尝试。', true, { recallMsg: 10 });
        }

        const input = e.msg.replace(/^m订阅\s*/, '').trim();
        const validFormat = /^([a-zA-Z0-9.-]+|\d{1,3}(\.\d{1,3}){3})(:\d+)?$/;

        if (!validFormat.test(input)) {
            return e.reply('请输入有效的服务器地址（格式：IP:端口 或 域名:端口）。', true, { recallMsg: 10 });
        }

        const subscriptions = this.loadSubscriptions();
        const serverData = subscriptions[input] || {
            server: input,
            subscribedGroups: [],
            subscribedAt: new Date().toISOString(),
            activeStats: {}
        };

        if (serverData.subscribedGroups.includes(e.group_id)) {
            return e.reply(`群组已经订阅了服务器：${input}，不能重复订阅。`, true, { recallMsg: 10 });
        }

        for (const server in subscriptions) {
            if (subscriptions[server].subscribedGroups.includes(e.group_id)) {
                return e.reply(`当前群组已经订阅了其他服务器：${server}，不能订阅多个服务器。`, true, { recallMsg: 10 });
            }
        }

        serverData.subscribedGroups.push(e.group_id);
        subscriptions[input] = serverData;
        this.saveSubscriptions(subscriptions);

        this.logger.info(`群组 ${e.group_id} 成功订阅了服务器：${input}`);
        e.reply(`已成功订阅服务器：${input}`);
    }

    // 取消订阅服务器（仅限群聊）
    unsubscribeServer(e) {
        if (!e.isGroup) {
            return e.reply('此功能仅限群聊使用，请在群聊中尝试。', true, { recallMsg: 10 });
        }

        const subscriptions = this.loadSubscriptions();
        const serverInfo = Object.values(subscriptions).find(s => s.subscribedGroups.includes(e.group_id));

        if (!serverInfo) {
            return e.reply('当前群未订阅任何服务器，无需取消订阅。', true, { recallMsg: 10 });
        }

        serverInfo.subscribedGroups = serverInfo.subscribedGroups.filter(groupId => groupId !== e.group_id);

        if (serverInfo.subscribedGroups.length === 0) {
            delete subscriptions[serverInfo.server];
        }

        this.saveSubscriptions(subscriptions);

        this.logger.info(`群组 ${e.group_id} 已取消订阅服务器：${serverInfo.server}`);
        e.reply(`已取消订阅服务器：${serverInfo.server}`);
    }

    // 查询服务器状态
    async checkServerStatus(e) {
        if (!e.isGroup) {
            return e.reply('此功能仅限群聊使用，请在群聊中尝试。', true, { recallMsg: 10 });
        }

        const subscriptions = this.loadSubscriptions();
        const serverInfo = Object.values(subscriptions).find(s => s.subscribedGroups.includes(e.group_id));

        if (!serverInfo) {
            return e.reply('当前群未订阅服务器，请使用 m订阅 <IP:端口> 进行订阅。', true, { recallMsg: 10 });
        }

        await e.reply(`正在查询服务器 ${serverInfo.server} 的状态，请稍后...`, true, { recallMsg: 10 });

        try {
            const serverStatus = new ServerStatus();
            const status = await serverStatus.getServerInfo(serverInfo.server);

            const imageUrl = this.getRandomBackgroundImage();
            // 修改渲染函数调用
            await renderAndSendMsgAuto(e, imageUrl, status, '服务器状态查询', `服务器 ${serverInfo.server} 的详细状态信息`);
        } catch (error) {
            console.error('查询服务器状态时发生错误:', error);
            this.logger.error(`查询服务器状态失败：${error.message}`);
            e.reply(`查询服务器状态失败：${error.message}`, true, { recallMsg: 10 });
        }
    }

    // 每小时记录服务器最高人数
    async recordHourlyStats() {
        const subscriptions = this.loadSubscriptions();
        const currentDate = getLocalDate();
        const currentHour = new Date().getHours();

        for (const serverAddress in subscriptions) {
            const { server } = subscriptions[serverAddress];

            try {
                const serverStatus = new ServerStatus();
                const data = await serverStatus.fetchServerStatus(server);

                // 如果获取不到状态数据或玩家人数无效，跳过当前服务器的记录
                if (!data || !data.players) {
                    this.logger.error(`服务器 ${server} 获取人数失败，跳过记录。`);
                    continue;
                }

                const onlinePlayers = parseInt(data.players.split('/')[0], 10) || 0;

                if (!subscriptions[serverAddress].activeStats[currentDate]) {
                    subscriptions[serverAddress].activeStats[currentDate] = Array(24).fill(0).join(',');
                }

                const hourlyData = subscriptions[serverAddress].activeStats[currentDate].split(',');
                const currentMax = parseInt(hourlyData[currentHour], 10) || 0;
                hourlyData[currentHour] = Math.max(currentMax, onlinePlayers).toString();
                subscriptions[serverAddress].activeStats[currentDate] = hourlyData.join(',');

                this.saveSubscriptions(subscriptions);
                this.logger.info(`服务器 ${server} 的当前小时最高在线人数已更新为 ${hourlyData[currentHour]}`);
            } catch (error) {
                this.logger.error(`记录在线人数时发生错误：${error.message}`);
            }
        }
    }

    // 自动启动定时任务
    autoStartTask() {
        if (this.intervalConfig === 0) {
            return this.logger.error("时间间隔配置为 0，插件不会自动启动任务！");
        }

        const { cronExpression } = handleTimeConfig(this.intervalConfig, this.name);
        addTaskToGroup("mc活跃统计", this.recordHourlyStats.bind(this), cronExpression);
    //    this.logger.info("已将 mc活跃统计 任务添加到任务组");
    }

    // 工具方法
    loadSubscriptions() {
        return JSON.parse(fs.readFileSync(SUBSCRIPTIONS_FILE, 'utf8'));
    }

    saveSubscriptions(subscriptions) {
        fs.writeFileSync(SUBSCRIPTIONS_FILE, JSON.stringify(subscriptions, null, 2));
    }

    getRandomBackgroundImage() {
        const images = JSON.parse(fs.readFileSync(BG_IMAGES_FILE, 'utf8'));
        const randomIndex = Math.floor(Math.random() * images.length);
        return images[randomIndex];
    }
}

export default ServerStatusPlugin;